package real.realschool;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;


import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import com.acecounter.logging.android.AMZLogEventAPI;
import com.acecounter.logging.android.AutoLoggingActivity;

import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.OnClickListener;

public class Real_WEB_Detail extends Activity {

	public static StaticAct Activity = StaticAct.getInstance();
	
	WebView wv;
	TextView home, write;
	Intent intent;
	Button cj_one, user, packages,sale, button, pic_button;
	Intent intend, paks,sales;
	EditText nick, commen;
	String ni, com, urlTime;
	private ProgressDialog progressDialog;
	
	private static final int REQ_CODE_PICK_IMAGE = 0;
	private static final int PICK_FROM_ALBUM = 1;
	private static final int CROP_FROM_CAMERA = 2;
	private static Bitmap LAST_BMP, FIRST_BMP, resizedx;
	/** Called when the activity is first created. */
	private static final int CAMERA_PIC_REQUEST = 1337;
	private static final String TEMP_PHOTO_FILE = "temporary_holder.jpg";
	Location lastLocation = null;
	private LocationManager locationMgr;
	double geo_w = 0, geo_g = 0;
	final static int GALLERY_RESULT = 0;
	private Uri mImageCaptureUri, imgUri, testUri;
	private Bitmap bmp;
	private ImageView imv;
	private String phoneNumber;
	private ArrayList<String> date;
	private Source source;
	
	Context context = null;
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		
		AMZLogEventAPI amzLog = AMZLogEventAPI.getInstance(this);
		amzLog.onViewPages(this);
	}
	
			
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.talk_web_detail);
		
		context = this;
		
		Activity.at.add(this);
		
		date = new ArrayList<String>();
		
		home = (TextView)findViewById(R.id.textView1);
		home.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
		
		TelephonyManager manager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		phoneNumber = manager.getLine1Number();
		
		open();
							
			
		write = (TextView)findViewById(R.id.textView4);
		write.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				LinearLayout li = (LinearLayout) View.inflate(Real_WEB_Detail.this, R.layout.real_dialog_re, null);
				
				nick = (EditText) li.findViewById(R.id.nick_var);
				commen = (EditText) li.findViewById(R.id.comment_var);
				
				
				if(phoneNumber.equals("01077376349")){
					nick.setText("정성준(개발자)");
				}
								
				final AlertDialog.Builder build = new AlertDialog.Builder(
						Real_WEB_Detail.this);
				build.setView(li)
						.setPositiveButton("확인",
								new DialogInterface.OnClickListener() {

									public void onClick(DialogInterface dialog,
											int which) {

										ni = " " + nick.getText().toString();
										com = " " + commen.getText().toString();

										WebView wv = (WebView) findViewById(R.id.webView); // 저장하는 곳이기때문에 웹뷰가 보일필요가없다
										wv.getSettings().setJavaScriptEnabled(
												true);

										Date today = new Date();
										SimpleDateFormat format = new SimpleDateFormat(
												"yyyy-MM-dd/hh:mm:ss"); 
										String strDate = format.format(today);

										TelephonyManager manager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); 
																															
										String phoneNumber = manager.getLine1Number();

										Toast.makeText(Real_WEB_Detail.this,
												"등록 되었습니다.", Toast.LENGTH_SHORT)
												.show();

										wv.loadUrl("http://"+Activity.ip+"/StudyProject/Realschool/real_re_input.jsp?&date="
												+ strDate
												+ "&nick="
												+ ni
												+ "&comment="
												+ com
												+ "&posit="
												+ Activity.posit
												+ "&phoneNum=" 
												+ phoneNumber);
										
										try {
											Thread.sleep(400);
										} catch (InterruptedException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
										
										
										wv = (WebView) findViewById(R.id.webView1); // 실제로 보여지는 부분
										//wv.setWebViewClient(new HelloWebViewClient());// progress bar 
										wv.getSettings().setJavaScriptEnabled(true);
										wv.loadUrl(Activity.detail_url);
									}
								})
						.setTitle("게시물 등록")
						.setMessage("게시물을 등록하시고 싶으면 \n 닉네임과 코멘트를 입력하시면 됩니다^^")
						.setNegativeButton("취소",
								new DialogInterface.OnClickListener() {

									public void onClick(DialogInterface dialog,
											int which) {
										// TODO Auto-generated method stub

									}
								}).show();

			}

		});
			
						
		wv = (WebView) findViewById(R.id.webView1);
		//wv.setWebViewClient(new HelloWebViewClient());
		wv.getSettings().setJavaScriptEnabled(true);
		wv.setHorizontalScrollBarEnabled(false);
		wv.setVerticalScrollBarEnabled(true);
		
		wv.loadUrl(Activity.detail_url);
		
	}
	
	public void open()
	{				
		
		try
		{
			process();
		}catch(IOException e)
		{
			e.printStackTrace();
		}
	}
	
	private void process() throws IOException
	{
		//상태 Progress 띄우기 위해서 사용함!
		final Handler mHandler = new Handler();
		new Thread()
		{

			@Override
			public void run()
			{
				URL nURL;
				try
				{
					nURL = new URL(Activity.detail_url);
															
					
					InputStream html = nURL.openStream();
					
					source = new Source(new InputStreamReader(html, "EUC-KR"));
					
					Activity.posit = ((Element)source.getAllElements(HTMLElementName.STRONG).get(0)).getContent().toString();
											
					
				}catch(IndexOutOfBoundsException e){
					e.printStackTrace();
				}catch (MalformedURLException e)
				{
					e.printStackTrace();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
				
			}
			
		}.start();
	}
			
	class HelloWebViewClient extends WebViewClient {
		ProgressDialog mProgress;

		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			
			view.loadUrl(url);
			
			return true;
		}

		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			if (mProgress == null) {
				mProgress = new ProgressDialog(Real_WEB_Detail.this);
				mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				mProgress.setTitle("로딩 중 ...");
				mProgress.setMessage("고객님들의 소중한 후기를 불러오고 있습니다^^");
				mProgress.setCancelable(false);

				mProgress.show();
			}
		}

		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {

		}

		public void onPageFinished(WebView view, String url) {
			if (mProgress.isShowing()) {
				mProgress.dismiss();
			}
		}
	}

	private Uri getTempUri() {
		return Uri.fromFile(getTempFile());
	}

	private boolean isSDCARDMounted() {
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED))
			return true;
		return false;
	}

	private File getTempFile() {
		if (isSDCARDMounted()) {

			File f = new File(Environment.getExternalStorageDirectory(),
					TEMP_PHOTO_FILE);
			try {
				f.createNewFile();
			} catch (IOException e) {

			}
			return f;
		} else {
			return null;
		}
	}

	private ProgressDialog loagindDialog;
	

	private Handler handler2 = new Handler() {
		public void handleMessage(Message msg) {
			loagindDialog.dismiss();
		}
	};
	

	public Drawable loadDrawable(String urlStr) {
		Drawable drawable = null;

		try {
			URL url = new URL(urlStr);
			InputStream is = url.openStream();
			drawable = Drawable.createFromStream(is, "none");
		} catch (Exception e) {
			// Log.e("LOG_TAG", "error, in loadDrawable \n" + e.toString());
		}

		return drawable;
	}

	public void onBackPressed() {
		if (wv.canGoBack()) {
			wv.goBack();
			//Intent men = new Intent(CGV_WEB_Detail.this, CGV_WEB.class);
			//startActivity(men);

		} else {
			super.onBackPressed();
		}
	}

}